﻿using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Xc.DataAccess.OneNetCore.Services
{
    public class DateTimeConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var text = reader.GetString();
            if (DateTime.TryParse(text, out var dt))
            {
                return dt;
            }
            else
            {
                return DateTime.MinValue;
            }
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("yyyy/MM/dd HH:mm:ss"));
        }
    }
}
